package cn.hackcloud.concurrency.balking;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.currentThread;

/**
 * 文档对象
 * Created by www.ibfbc.com
 */
public class Document {
    //如果文档发生改变，changed会被设置为true
    private boolean changed = false;
    //一次需要保存的内容，可以将其理解为内容缓存
    private List<String> content = new ArrayList<>();

    private final FileWriter writer;
    //自动保存文档的线程
    private static AutoSaveThread autoSaveThread;

    //构造函数需要传入文档保存的路径和文档名称
    private Document(String documentPath, String documentName) throws IOException {
        this.writer = new FileWriter(new File(documentPath, documentName));
    }

    //创建文档，随便启动自动保存文档的线程
    public static Document create(String documentPath, String documentName) throws IOException {
        Document document = new Document(documentPath, documentName);
        autoSaveThread = new AutoSaveThread(document);
        autoSaveThread.start();
        return document;
    }

    //文档的编辑，其实就是向content队列中提交字符串
    public void edit(String content) {
        synchronized (this) {
            this.content.add(content);
            this.changed = true;
        }
    }

    //文档的编辑，其实就是向content队列中提交字符串
    public void close() throws IOException {
        autoSaveThread.interrupt();
        writer.close();
    }

    //外部显示调用存储
    public void save() throws IOException {
        synchronized (this) {
            //balking，如果文档已经被保存了则之间返回
            if (!changed) {
                return;
            }
        }
        System.out.println(currentThread() + " execute the save action.");
        for (String cacheLine : content) {
            this.writer.write(cacheLine);
            this.writer.write("\r\n");
        }
        this.writer.flush();
        //表示没有新的内容
        this.changed = false;
        this.content.clear();
    }
}
